#!usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: muchen
@file: base.py
@time: 2024/12/25
"""
import random
import traceback

from selenium.common import NoAlertPresentException
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from autoTest_ecshop.utils.file_utils import open_yaml
from autoTest_ecshop.utils.log_util import logger

url = open_yaml("common.yaml").get("url")


class BasePage:
    def __init__(self, driver):
        self.driver = driver
        # self.driver.get(url)
        self.wait = WebDriverWait(self.driver, 10)

    # 查找单个元素
    def find_element(self, locator):
        try:
            element = self.wait.until(EC.presence_of_element_located(locator))
            logger.info(f"查找元素 {locator} 成功")
            return element
        except:
            logger.error(f"查找元素 {locator} 失败。错误信息如下：\n{traceback.format_exc()}")
            raise

    # 在输入框中输入信息
    def input_text(self, locator, text):
        logger.info(f"在元素 {locator} 中输入信息 {text}")
        element = self.find_element(locator)
        element.clear()
        element.send_keys(text)

    # 点击元素
    def click(self, locator):
        logger.info(f"点击元素 {locator}")
        self.find_element(locator).click()

    # 警告框的处理
    def alert_handle(self, inputData="", text=False, action=False):
        # 判断是否弹出警告框，并获取警告框的文本
        logger.info("处理警告框")
        res = None
        try:
            alert = self.driver.switch_to.alert
            alert_text = alert.text
        except NoAlertPresentException:
            alert_text = ""
            pass
        if alert_text != "":
            logger.info("切换到警告框")
            # alert = self.driver.switch_to.alert
            if len(inputData) != 0:
                logger.info("在警告框中输入信息")
                alert.send_keys(inputData)
            if text:
                logger.info("获取警告框的文本")
                res = alert_text
            if action:
                logger.info("点击警告框的确定按钮")
                alert.accept()
            else:
                logger.info("点击警告框的取消按钮")
                alert.dismiss()
            return res

    # 切换frame
    def switch_frame(self, locator):
        logger.info(f"切换到frame {locator}")
        self.driver.switch_to.frame(self.find_element(locator))

    # 在下拉框中随机选择一个选项
    def select_random(self, locator, is_product=False):
        if is_product:
            # 通过js获取ele_product的display属性
            js = 'return document.getElementsByName("product_id")[0].style.display;'
            if self.driver.execute_script(js) == 'none':
                return
        logger.info(f"在元素 {locator} 中随机选择一个选项")
        element = self.find_element(locator)
        max_index = len(Select(element).options) - 1
        if max_index > 0:
            Select(element).select_by_index(random.randint(0, max_index))

    # 活动时间文本框处理
    def activity_time(self, locator):
        logger.info(f"处理活动时间文本框 {locator}")
        # 移除文本框可读属性
        element = self.find_element(locator)
        js = f'document.getElementsByName(\"{str(locator[1])}\")[0].removeAttribute("readonly");'
        self.driver.execute_script(js)
